/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Dao;

import Dao.exceptions.NonexistentEntityException;
import Dao.exceptions.PreexistingEntityException;
import Logica.Colaborador;
import java.io.Serializable;
import javax.persistence.Query;
import javax.persistence.EntityNotFoundException;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import Logica.Usuario;
import Logica.Evento;
import Logica.Competencia;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;

/**
 *
 * @author User
 */
public class ColaboradorJpaController implements Serializable {

    public ColaboradorJpaController(EntityManagerFactory emf) {
        this.emf = emf;
    }
    private EntityManagerFactory emf = null;

    public EntityManager getEntityManager() {
        return emf.createEntityManager();
    }

    public void create(Colaborador colaborador) throws PreexistingEntityException, Exception {
        if (colaborador.getCompetenciaCollection() == null) {
            colaborador.setCompetenciaCollection(new ArrayList<Competencia>());
        }
        if (colaborador.getEventoCollection() == null) {
            colaborador.setEventoCollection(new ArrayList<Evento>());
        }
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            Usuario login = colaborador.getLogin();
            if (login != null) {
                login = em.getReference(login.getClass(), login.getLogin());
                colaborador.setLogin(login);
            }
            Evento idEvento = colaborador.getIdEvento();
            if (idEvento != null) {
                idEvento = em.getReference(idEvento.getClass(), idEvento.getIdEvento());
                colaborador.setIdEvento(idEvento);
            }
            Collection<Competencia> attachedCompetenciaCollection = new ArrayList<Competencia>();
            for (Competencia competenciaCollectionCompetenciaToAttach : colaborador.getCompetenciaCollection()) {
                competenciaCollectionCompetenciaToAttach = em.getReference(competenciaCollectionCompetenciaToAttach.getClass(), competenciaCollectionCompetenciaToAttach.getIdCompetencia());
                attachedCompetenciaCollection.add(competenciaCollectionCompetenciaToAttach);
            }
            colaborador.setCompetenciaCollection(attachedCompetenciaCollection);
            Collection<Evento> attachedEventoCollection = new ArrayList<Evento>();
            for (Evento eventoCollectionEventoToAttach : colaborador.getEventoCollection()) {
                eventoCollectionEventoToAttach = em.getReference(eventoCollectionEventoToAttach.getClass(), eventoCollectionEventoToAttach.getIdEvento());
                attachedEventoCollection.add(eventoCollectionEventoToAttach);
            }
            colaborador.setEventoCollection(attachedEventoCollection);
            em.persist(colaborador);
            if (login != null) {
                login.getColaboradorCollection().add(colaborador);
                login = em.merge(login);
            }
            if (idEvento != null) {
                Colaborador oldIdDirectorOfIdEvento = idEvento.getIdDirector();
                if (oldIdDirectorOfIdEvento != null) {
                    oldIdDirectorOfIdEvento.setIdEvento(null);
                    oldIdDirectorOfIdEvento = em.merge(oldIdDirectorOfIdEvento);
                }
                idEvento.setIdDirector(colaborador);
                idEvento = em.merge(idEvento);
            }
            for (Competencia competenciaCollectionCompetencia : colaborador.getCompetenciaCollection()) {
                competenciaCollectionCompetencia.getColaboradorCollection().add(colaborador);
                competenciaCollectionCompetencia = em.merge(competenciaCollectionCompetencia);
            }
            for (Evento eventoCollectionEvento : colaborador.getEventoCollection()) {
                Colaborador oldIdDirectorOfEventoCollectionEvento = eventoCollectionEvento.getIdDirector();
                eventoCollectionEvento.setIdDirector(colaborador);
                eventoCollectionEvento = em.merge(eventoCollectionEvento);
                if (oldIdDirectorOfEventoCollectionEvento != null) {
                    oldIdDirectorOfEventoCollectionEvento.getEventoCollection().remove(eventoCollectionEvento);
                    oldIdDirectorOfEventoCollectionEvento = em.merge(oldIdDirectorOfEventoCollectionEvento);
                }
            }
            em.getTransaction().commit();
        } catch (Exception ex) {
            if (findColaborador(colaborador.getIdColaborador()) != null) {
                throw new PreexistingEntityException("Colaborador " + colaborador + " already exists.", ex);
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void edit(Colaborador colaborador) throws NonexistentEntityException, Exception {
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            Colaborador persistentColaborador = em.find(Colaborador.class, colaborador.getIdColaborador());
            Usuario loginOld = persistentColaborador.getLogin();
            Usuario loginNew = colaborador.getLogin();
            Evento idEventoOld = persistentColaborador.getIdEvento();
            Evento idEventoNew = colaborador.getIdEvento();
            Collection<Competencia> competenciaCollectionOld = persistentColaborador.getCompetenciaCollection();
            Collection<Competencia> competenciaCollectionNew = colaborador.getCompetenciaCollection();
            Collection<Evento> eventoCollectionOld = persistentColaborador.getEventoCollection();
            Collection<Evento> eventoCollectionNew = colaborador.getEventoCollection();
            if (loginNew != null) {
                loginNew = em.getReference(loginNew.getClass(), loginNew.getLogin());
                colaborador.setLogin(loginNew);
            }
            if (idEventoNew != null) {
                idEventoNew = em.getReference(idEventoNew.getClass(), idEventoNew.getIdEvento());
                colaborador.setIdEvento(idEventoNew);
            }
            Collection<Competencia> attachedCompetenciaCollectionNew = new ArrayList<Competencia>();
            for (Competencia competenciaCollectionNewCompetenciaToAttach : competenciaCollectionNew) {
                competenciaCollectionNewCompetenciaToAttach = em.getReference(competenciaCollectionNewCompetenciaToAttach.getClass(), competenciaCollectionNewCompetenciaToAttach.getIdCompetencia());
                attachedCompetenciaCollectionNew.add(competenciaCollectionNewCompetenciaToAttach);
            }
            competenciaCollectionNew = attachedCompetenciaCollectionNew;
            colaborador.setCompetenciaCollection(competenciaCollectionNew);
            Collection<Evento> attachedEventoCollectionNew = new ArrayList<Evento>();
            for (Evento eventoCollectionNewEventoToAttach : eventoCollectionNew) {
                eventoCollectionNewEventoToAttach = em.getReference(eventoCollectionNewEventoToAttach.getClass(), eventoCollectionNewEventoToAttach.getIdEvento());
                attachedEventoCollectionNew.add(eventoCollectionNewEventoToAttach);
            }
            eventoCollectionNew = attachedEventoCollectionNew;
            colaborador.setEventoCollection(eventoCollectionNew);
            colaborador = em.merge(colaborador);
            if (loginOld != null && !loginOld.equals(loginNew)) {
                loginOld.getColaboradorCollection().remove(colaborador);
                loginOld = em.merge(loginOld);
            }
            if (loginNew != null && !loginNew.equals(loginOld)) {
                loginNew.getColaboradorCollection().add(colaborador);
                loginNew = em.merge(loginNew);
            }
            if (idEventoOld != null && !idEventoOld.equals(idEventoNew)) {
                idEventoOld.setIdDirector(null);
                idEventoOld = em.merge(idEventoOld);
            }
            if (idEventoNew != null && !idEventoNew.equals(idEventoOld)) {
                Colaborador oldIdDirectorOfIdEvento = idEventoNew.getIdDirector();
                if (oldIdDirectorOfIdEvento != null) {
                    oldIdDirectorOfIdEvento.setIdEvento(null);
                    oldIdDirectorOfIdEvento = em.merge(oldIdDirectorOfIdEvento);
                }
                idEventoNew.setIdDirector(colaborador);
                idEventoNew = em.merge(idEventoNew);
            }
            for (Competencia competenciaCollectionOldCompetencia : competenciaCollectionOld) {
                if (!competenciaCollectionNew.contains(competenciaCollectionOldCompetencia)) {
                    competenciaCollectionOldCompetencia.getColaboradorCollection().remove(colaborador);
                    competenciaCollectionOldCompetencia = em.merge(competenciaCollectionOldCompetencia);
                }
            }
            for (Competencia competenciaCollectionNewCompetencia : competenciaCollectionNew) {
                if (!competenciaCollectionOld.contains(competenciaCollectionNewCompetencia)) {
                    competenciaCollectionNewCompetencia.getColaboradorCollection().add(colaborador);
                    competenciaCollectionNewCompetencia = em.merge(competenciaCollectionNewCompetencia);
                }
            }
            for (Evento eventoCollectionOldEvento : eventoCollectionOld) {
                if (!eventoCollectionNew.contains(eventoCollectionOldEvento)) {
                    eventoCollectionOldEvento.setIdDirector(null);
                    eventoCollectionOldEvento = em.merge(eventoCollectionOldEvento);
                }
            }
            for (Evento eventoCollectionNewEvento : eventoCollectionNew) {
                if (!eventoCollectionOld.contains(eventoCollectionNewEvento)) {
                    Colaborador oldIdDirectorOfEventoCollectionNewEvento = eventoCollectionNewEvento.getIdDirector();
                    eventoCollectionNewEvento.setIdDirector(colaborador);
                    eventoCollectionNewEvento = em.merge(eventoCollectionNewEvento);
                    if (oldIdDirectorOfEventoCollectionNewEvento != null && !oldIdDirectorOfEventoCollectionNewEvento.equals(colaborador)) {
                        oldIdDirectorOfEventoCollectionNewEvento.getEventoCollection().remove(eventoCollectionNewEvento);
                        oldIdDirectorOfEventoCollectionNewEvento = em.merge(oldIdDirectorOfEventoCollectionNewEvento);
                    }
                }
            }
            em.getTransaction().commit();
        } catch (Exception ex) {
            String msg = ex.getLocalizedMessage();
            if (msg == null || msg.length() == 0) {
                String id = colaborador.getIdColaborador();
                if (findColaborador(id) == null) {
                    throw new NonexistentEntityException("The colaborador with id " + id + " no longer exists.");
                }
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void destroy(String id) throws NonexistentEntityException {
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            Colaborador colaborador;
            try {
                colaborador = em.getReference(Colaborador.class, id);
                colaborador.getIdColaborador();
            } catch (EntityNotFoundException enfe) {
                throw new NonexistentEntityException("The colaborador with id " + id + " no longer exists.", enfe);
            }
            Usuario login = colaborador.getLogin();
            if (login != null) {
                login.getColaboradorCollection().remove(colaborador);
                login = em.merge(login);
            }
            Evento idEvento = colaborador.getIdEvento();
            if (idEvento != null) {
                idEvento.setIdDirector(null);
                idEvento = em.merge(idEvento);
            }
            Collection<Competencia> competenciaCollection = colaborador.getCompetenciaCollection();
            for (Competencia competenciaCollectionCompetencia : competenciaCollection) {
                competenciaCollectionCompetencia.getColaboradorCollection().remove(colaborador);
                competenciaCollectionCompetencia = em.merge(competenciaCollectionCompetencia);
            }
            Collection<Evento> eventoCollection = colaborador.getEventoCollection();
            for (Evento eventoCollectionEvento : eventoCollection) {
                eventoCollectionEvento.setIdDirector(null);
                eventoCollectionEvento = em.merge(eventoCollectionEvento);
            }
            em.remove(colaborador);
            em.getTransaction().commit();
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public List<Colaborador> findColaboradorEntities() {
        return findColaboradorEntities(true, -1, -1);
    }

    public List<Colaborador> findColaboradorEntities(int maxResults, int firstResult) {
        return findColaboradorEntities(false, maxResults, firstResult);
    }

    private List<Colaborador> findColaboradorEntities(boolean all, int maxResults, int firstResult) {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            cq.select(cq.from(Colaborador.class));
            Query q = em.createQuery(cq);
            if (!all) {
                q.setMaxResults(maxResults);
                q.setFirstResult(firstResult);
            }
            return q.getResultList();
        } finally {
            em.close();
        }
    }

    public Colaborador findColaborador(String id) {
        EntityManager em = getEntityManager();
        try {
            return em.find(Colaborador.class, id);
        } finally {
            em.close();
        }
    }

    public int getColaboradorCount() {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            Root<Colaborador> rt = cq.from(Colaborador.class);
            cq.select(em.getCriteriaBuilder().count(rt));
            Query q = em.createQuery(cq);
            return ((Long) q.getSingleResult()).intValue();
        } finally {
            em.close();
        }
    }
    
}
